var webSocket;

export class DCISocketServer {
    constructor (config) {
        Object.assign(this, config);
        
        // 连接状态
        // 0-未连接 1-连接成功 2-连接已关闭 3-连接失败
        this.readyState = 0;

        // 初始化
        this.onWebSocketConnect();
    }
    // webSocket连接
    onWebSocketConnect () {
        
        if (!webSocket || webSocket.state != 1) {
            webSocket = $.connection("http://localhost:8085/unit");
            webSocket.logging = true;
            
            // 连接完成后要做的事情
            this.onOpen();
            this.onMessage(this.onMessageDone);
            this.onError();
        }
    };
    // webSocket连接建立后触发
    onOpen (callback) {
        webSocket.start().done((event)=>{
            this.readyState = 1;
            callback && callback(event);
        })
    };
    // webSocket在客户端接收服务端数据时触发
    onMessage (callback) {
        webSocket.received((data)=>{
            if ( data.state == "0" ) {
                callback && callback(data);
            } 
        })
    }; 
    // webSocket通信发生错误时触发
    onError () {
        webSocket.error((err)=>{
            webSocket.stop();
            
            webSocket = null;

            this.readyState = 3;

            this.onWebSocketError && this.onWebSocketError(err);

            console.error("WebSocket error observed:", err);
        })
    };
    // 关闭webSocket连接
    close () {
        this.readyState = 2;
        webSocket.stop();
    };
    // webSocket使用连接发送数据
    send (data) {
        webSocket.send( data )	
    };
    // 回调方法（更大权限地去使用）
    then (callback) {
        callback && callback(this, webSocket);
    };
    // 返回设备地址
    getMacAddr (params) {
        let jsondt = { callname: "test", params };
        let count = 0;
        let isSendToCheck = ()=>{
            if ( this.readyState==1 ) {
                this.send(jsondt);
            } else {
                ++count;
                setTimeout(isSendToCheck, 100);
            }
        };

        setTimeout(isSendToCheck, 100);
    }
}
